import request from "./request"
import store from "../store/index"
import { userActionType } from "../store/modules/user"
import { checkBindPhone, handleUrlParams, showModal } from "./index"

const behaviorFun = {
	//展示弹窗
	showPopup(data, eventQueue, popupInstance) {
		popupInstance.addPopupItem(
			data.boxPicture,
			() => {
				eventQueue.shift()
				//执行下一个推荐官队列行为
				publicFun.dispatchRecommenderBehavior()
			},
		)
	},
	//发送请求领取福利
	receiveWelfare(data, eventQueue) {
		return new Promise((resolve, reject) => {
			request({
				url: data.welfareUrl,
				errorHandle: true,
				showLoading: true,
			})
				.then(async () => {
					//执行下一个行为
					eventQueue.shift()
					await showModal({
						title: "提示",
						content: "领取成功",
						showCancel: false,
					})
					publicFun.dispatchRecommenderBehavior()
					resolve()
				})
				.catch((err) => {
					reject(err)
				})
		})
	},
	//跳转页面
	jumpPage(data, eventQueue) {
		uni.redirectTo({
			url: handleUrlParams(
				data.jumpPage,
				{
					redirectUrl: encodeURIComponent("/pages/index/index"),
				},
			),
		})
		eventQueue.shift()
	},
	//展示弹框详情文案页面
	showPopupDetail(data, eventQueue) {
		uni.navigateTo({
			url: "/markingCampaign/pages/recommender/posterDetail/index",
		})
		eventQueue.shift()
	},
}
const publicFun = {
	//获取推荐官行为
	getRecommenderBehavior() {
		return new Promise((resolve, reject) => {
			if (!store.getters[userActionType.getters.recommender.id]) {
				resolve({
					eventQueue: [],
					data: {},
				})
				return
			}
			request({
				url: "userSharePoster/getPosterDetails",
				data: {
					userId: store.getters[userActionType.getters.recommender.id],
					platformCode: "4",
				},
				errorHandle: true,
			})
				.then((data) => {
					//根据后台配置解析事件队列
					const eventQueue = []
					//检查是否需要弹窗
					if (data.scanCodeBox === 1 && data.boxPicture) {
						eventQueue.push("showPopup")
					}
					//检查是否需要跳转到详情文案页面
					if (data.boxDetailsPicture) {
						eventQueue.push("showPopupDetail")
					}
					//检查是否需要发送请求领取福利
					if (data.welfareUrl) {
						eventQueue.push("receiveWelfare")
					}
					//检查是否需要跳转页面
					if (data.jumpPage) {
						eventQueue.push("jumpPage")
					}
					const behavior = {
						eventQueue,
						data,
					}
					store.commit(userActionType.mutations.recommender.behavior, behavior)
					resolve(behavior)
				})
				.catch((err) => {
					reject(err)
				})
		})
	},
	//触发推荐官行为
	async dispatchRecommenderBehavior(popupInstance) {
		let behavior = store.getters[userActionType.getters.recommender.behavior]
		if (!behavior) {
			behavior = await this.getRecommenderBehavior()
		}
		if (behavior.eventQueue.length > 0) {
			//绑定手机号码
			if (!await checkBindPhone("/pages/index/index")) {
				return
			}
			behaviorFun[behavior.eventQueue[0]](behavior.data, behavior.eventQueue, popupInstance)
		}
		return behavior.eventQueue.length > 0
	},
}

export default publicFun
